package sample;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Lists all the active Wave conversations
 * @author ago
 *
 */
@SuppressWarnings("serial")
public class ListWavesServlet extends HttpServlet {
  @SuppressWarnings("unchecked")
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    String alt = request.getParameter("alt");
    String callback = request.getParameter("callback");
    PersistenceManager pm = PMF.get().getPersistenceManager();
    String query = "select from " + WaveletRecord.class.getName() + " order by date desc";
    List<WaveletRecord> waveletRecords = (List<WaveletRecord>) pm.newQuery(query).execute();

    if(alt != null && alt.equals("json-in-script")) {
      if(callback == null || callback.equals("")) {
        callback = "callback";
      }
      try {
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        for(WaveletRecord waveletRecord : waveletRecords) {
          JSONObject item = new JSONObject();
          item.put("title", waveletRecord.getTitle());
          item.put("numParticipants", waveletRecord.getNumParticipants());
          item.put("date", waveletRecord.getDate());
          item.put("waveId", waveletRecord.getWaveId());
          jsonObjects.add(item);
        }
        JSONObject output = new JSONObject();
        output.put("wavelets", jsonObjects);
        response.getWriter().println(callback + "(" + output.toString() + ")");
      } catch (JSONException e) {
        e.printStackTrace();
        throw new ServletException(e);
      }
    } else {      
      request.setAttribute("waveletRecords", waveletRecords);
      request.getRequestDispatcher("listWaves.jsp").forward(request, response);
    }
  }
}
